package com.selfdiscipline.ui.navigation

import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.BarChart
import androidx.compose.material.icons.filled.DateRange
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.filled.Timer
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import androidx.navigation.NavGraph.Companion.findStartDestination
import androidx.navigation.NavHostController
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.navArgument
import com.selfdiscipline.R
import com.selfdiscipline.ui.screens.habit.HabitDetailScreen
import com.selfdiscipline.ui.screens.habit.HabitScreen
import com.selfdiscipline.ui.screens.statistics.StatisticsScreen
import com.selfdiscipline.ui.screens.task.TaskScreen
import com.selfdiscipline.ui.screens.task.TaskDetailScreen
import com.selfdiscipline.ui.screens.task.TaskAddEditScreen
import com.selfdiscipline.ui.screens.timer.TimerScreen
import com.selfdiscipline.ui.screens.settings.SettingsScreen

/**
 * Main navigation graph for the app
 */
@Composable
fun AppNavGraph(
    navController: NavHostController,
    modifier: Modifier = Modifier
) {
    NavHost(
        navController = navController,
        startDestination = Screen.Task.route,
        modifier = modifier
    ) {
        // Tasks screen
        composable(Screen.Task.route) {
            TaskScreen(
                navigateToTaskDetail = { taskId ->
                    navController.navigate(Screen.TaskDetail.createRoute(taskId))
                },
                navigateToAddTask = {
                    navController.navigate(Screen.TaskAddEdit.createRoute())
                }
            )
        }
        
        // Task detail screen
        composable(
            route = Screen.TaskDetail.route,
            arguments = listOf(navArgument("taskId") { type = NavType.LongType })
        ) { backStackEntry ->
            val taskId = backStackEntry.arguments?.getLong("taskId") ?: 0L
            TaskDetailScreen(
                taskId = taskId,
                navigateBack = { navController.popBackStack() },
                navigateToEditTask = { taskId ->
                    navController.navigate(Screen.TaskAddEdit.createRoute(taskId))
                }
            )
        }
        
        // Task add/edit screen
        composable(
            route = Screen.TaskAddEdit.route,
            arguments = listOf(navArgument("taskId") { 
                type = NavType.LongType
                defaultValue = -1L
                nullable = false 
            })
        ) { backStackEntry ->
            val taskId = backStackEntry.arguments?.getLong("taskId") ?: -1L
            val finalTaskId = if (taskId == -1L) null else taskId
            
            TaskAddEditScreen(
                taskId = finalTaskId,
                navigateBack = { navController.popBackStack() }
            )
        }
        
        // Timer screen
        composable(Screen.Timer.route) {
            TimerScreen(
                navController = navController,
                navigateToTask = { navController.navigate(Screen.Task.route) },
                navigateToHabit = { navController.navigate(Screen.Habit.route) },
                navigateToSettings = { navController.navigate(Screen.Settings.route) }
            )
        }
        
        // Habits screen
        composable(Screen.Habit.route) {
            HabitScreen(
                navigateToHabitDetail = { habitId ->
                    navController.navigate(Screen.HabitDetail.createRoute(habitId))
                },
                navigateToAddHabit = {
                    // 添加习惯的跳转逻辑
                },
                navController = navController
            )
        }
        
        // Habit detail screen
        composable(
            route = Screen.HabitDetail.route,
            arguments = listOf(navArgument("habitId") { type = NavType.LongType })
        ) { backStackEntry ->
            val habitId = backStackEntry.arguments?.getLong("habitId") ?: 0L
            HabitDetailScreen(
                habitId = habitId,
                navigateUp = { navController.popBackStack() },
                navigateToEditHabit = { /* 编辑习惯跳转 */ }
            )
        }
        
        // Statistics screen
        composable(Screen.Statistics.route) {
            StatisticsScreen(navController = navController)
        }
        
        // Settings screen
        composable(Screen.Settings.route) {
            SettingsScreen()
        }
    }
}

// 更新Screen密封类，添加新的导航目标
sealed class Screen(val route: String) {
    object Task : Screen("task")
    object TaskDetail : Screen("task/{taskId}") {
        fun createRoute(taskId: Long) = "task/$taskId"
    }
    object TaskAddEdit : Screen("task/edit/{taskId}") {
        fun createRoute(taskId: Long? = null) = 
            if (taskId != null) "task/edit/$taskId" else "task/edit/-1"
    }
    object Timer : Screen("timer")
    object Habit : Screen("habit")
    object HabitDetail : Screen("habit/{habitId}") {
        fun createRoute(habitId: Long) = "habit/$habitId"
    }
    object Statistics : Screen("statistics")
    object Settings : Screen("settings")
}

/**
 * Bottom navigation bar
 */
@Composable
fun BottomNavigationBar(
    navController: NavHostController,
    modifier: Modifier = Modifier
) {
    val items = listOf(
        NavigationItem(
            route = Screen.Task.route,
            icon = Icons.Filled.Home,
            labelResId = R.string.nav_task
        ),
        NavigationItem(
            route = Screen.Timer.route,
            icon = Icons.Filled.Timer,
            labelResId = R.string.nav_timer
        ),
        NavigationItem(
            route = Screen.Habit.route,
            icon = Icons.Filled.DateRange,
            labelResId = R.string.nav_habit
        ),
        NavigationItem(
            route = Screen.Statistics.route,
            icon = Icons.Filled.BarChart,
            labelResId = R.string.stats_title
        ),
        NavigationItem(
            route = Screen.Settings.route,
            icon = Icons.Filled.Settings,
            labelResId = R.string.nav_settings
        )
    )
    
    val navBackStackEntry by navController.currentBackStackEntryAsState()
    val currentRoute = navBackStackEntry?.destination?.route
    
    NavigationBar(
        modifier = modifier,
        containerColor = MaterialTheme.colorScheme.surface
    ) {
        items.forEach { item ->
            NavigationBarItem(
                icon = { 
                    Icon(
                        imageVector = item.icon,
                        contentDescription = stringResource(id = item.labelResId)
                    )
                },
                label = { Text(stringResource(id = item.labelResId)) },
                selected = currentRoute == item.route,
                onClick = {
                    if (currentRoute != item.route) {
                        navController.navigate(item.route) {
                            // Pop up to the start destination of the graph
                            popUpTo(navController.graph.findStartDestination().id) {
                                saveState = true
                            }
                            // Avoid multiple copies of the same destination
                            launchSingleTop = true
                            // Restore state when reselecting a previously selected item
                            restoreState = true
                        }
                    }
                }
            )
        }
    }
}

/**
 * Data class representing an item in the bottom navigation
 */
data class NavigationItem(
    val route: String,
    val icon: ImageVector,
    val labelResId: Int
) 